// pages/sell/sell.js
const db = wx.cloud.database()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    value1: '',
    value2: '',
    value3: '',
    value4: '',
    src: null,
    array: [
      "书籍",
      "服饰",
      "鞋子",
      
      "电器",
     
      "手机",
      "零食",
      "数码"
    ],
    index: 0,
  },
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
  },
  //确认提交
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value);
    let that=this;
    //let name = e.detail.value.name+".jpg";
    let index=that.data.index;
    let time= new Date().getTime()
    db.collection('users').add({
      // data 字段表示需新增的 JSON 数据
      data: {
        price: e.detail.value.price,
        name: e.detail.value.name,
        content: e.detail.value.content,
        species: that.data.array[index],
        src:"",
        time: time
      }
    }).then(result => {
      let name = time+".jpg";
      let id = result._id;
      wx.cloud.uploadFile({
        cloudPath: name,
        filePath: that.data.src,
        success(res) { 
          //上传成功后会返回永久地址  res.fileID
          //更新src
          db.collection('users').doc(id).update({
            // data 传入需要局部更新的数据
            data: {
              src: res.fileID
            }
          }).then(sec => {
            console.log("更新成功")
            console.log(sec);
          })
        }
      })
      wx.showToast({
        title: '上架成功',
      });
      setTimeout(function(){
        wx.navigateBack({})
      },1000)
    }).catch(console.error)
  },
  onLoad: function(options) {

  },
   //选择图片
  choose: function() {
    let that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        //选择完成会先返回一个临时地址保存备用
        const tempFilePaths = res.tempFilePaths
        that.setData({
          src: tempFilePaths[0]
        })
      }
    })
  }
})